from datetime import date
import time

from entity.mistake_details import Mistake_details
from entity.mistake_history import Mistake_history
from database.database import Database


class UPDATE:
    def __init__(self,uid,type,details,reason):
        self.uid=uid
        self.type=type
        self.details=details
        self.reason=reason

    def init_in_history_update_in_details(self):
        # 初始化历史错误
        db = Database()

        # 先记录到历史错误信息表中
        id = int(time.time())
        obj = Mistake_history(id, self.uid, self.type, self.details, date.today(),  self.reason)
        db.insert_mistake_history(obj)

        # 从mistake_Details中找到相同人犯的相同类型错误
        middle_object = db.get_mistake_details_by_uid_type_details(obj.uid,obj.type,obj.details)

        # 获取错误类型ID
        mistake_details_id = middle_object[0][0]

        # 通过 错误类型和细节 更新犯错次数、权重与最新犯错时间
        db.update_mistake_details(8,1,self.uid,mistake_details_id,date.today())

        # 获取之前最新犯错次数和犯错时间，计算两次错误相邻的犯错时间
        times = middle_object[0][2]
        latestDate = middle_object[0][1]

        # 如果犯错次数超过一次，那么就有必要重新更新权重了
        if times > 0:
            # 计算两次错误时间间隔
            gap = (date.today() - latestDate).days
            if gap < 1:
                # 更新错误类型占比
                weight_plus = 9
            elif 1 <= gap < 4:
                weight_plus = 7
            elif 4 <= gap < 7:
                weight_plus = 5
            elif 7 <= gap < 30:
                weight_plus = 3
            else:
                weight_plus = 1
            db.update_mistake_details(weight_plus,0, self.uid,mistake_details_id, date.today())

        db.close_connection()